package com.cetsk.android.talkorigins;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class ClaimViewActivity extends Activity {
	WebView webview;

	private ProgressDialog dialog;

	Boolean isFav = false;
	String html = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		dialog = ProgressDialog.show(this,"Loading", "Loading claim...",true);
		new Thread() {
			public void run() {
				try{
					Claim claim = (Claim) getIntent().getSerializableExtra("claim");
					setTitle(claim.getName());
					HTMLParse hp = new HTMLParse(getApplicationContext());
					html = hp.getHtml("http://www.talkorigins.org/indexcc/"+claim.getUrl());
					html = html.replaceAll("\\.\\./", "http://talkorigins.org/indexcc/");
				} catch (Exception e) { }
				handler.sendEmptyMessage(0);
				dialog.dismiss(); 
			}
		}.start();
		super.onCreate(savedInstanceState);
	}
	
	public void setFavStatus(View button) {
		ToggleButton tb = (ToggleButton) button;
		Boolean status = tb.isChecked();
		
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		DatabaseHelper dbh = new DatabaseHelper(this);
		// Set the fav status
		isFav = status;
		
		setFavStatus( claim, dbh );
		
	}
	
	public void setFavStatus( Claim claim, DatabaseHelper dbh ) {
		try {
			if ( favRecordExists( claim, dbh ) ) {
				updateFavRecord( claim, dbh );
			} else {
				insertFavRecord( claim, dbh);	
			}
		} catch (SQLException sqle ) {
			Toast.makeText(getApplicationContext(), "Error adding favorite: "+sqle.getMessage(), Toast.LENGTH_SHORT).show();
			Log.e("SQLError",sqle.getMessage());
		} finally {
			dbh.close();
		}
		
		if ( isFav ) {
			Toast.makeText(getApplicationContext(),"Added to your favourites", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(getApplicationContext(),"Removed from your favourites", Toast.LENGTH_SHORT).show();
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			setContentView(R.layout.claim_view);
			webview = (WebView) findViewById(R.id.webview);

			if(html != null && html.length() > 0){
				webview.loadData(html, "text/html", "utf-8");
			} else {
				Toast.makeText(getApplicationContext(),"There was a problem fetching HTML.", Toast.LENGTH_SHORT).show();
				Log.i("HTML_ERROR", "Could not Parse");
			}
			
		// This is intended to indicate whether the object is currently a favourite or not.
		isFav = getFavouriteState();
		ToggleButton tb = (ToggleButton) findViewById( R.id.favToggle1 );
		tb.setChecked(isFav);
			
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.claim_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.favorite:
			onAddFavorite(webview);
			return true;
		case R.id.url:
			onClipboard(webview);
			return true;
		case R.id.share:
			onShare(webview);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onShare(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		String url = "http://www.talkorigins.org/indexcc/" + claim.getUrl();
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TalkOrigins article: " + claim.getName());
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);

		startActivity(Intent.createChooser(shareIntent, "Share via..."));
	}
	public void onClipboard(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		String url = "http://www.talkorigins.org/indexcc/" + claim.getUrl();
		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
		clipboard.setText(url);
		Toast.makeText(getApplicationContext(), "URL \""+url+"\" copied to clipboard.", Toast.LENGTH_SHORT).show();
	}

	public void onViewSiblings(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		Intent intent = new Intent(v.getContext(), ClaimsListActivity.class);
		Claim c  = new Claim();
		c.setId(claim.getParentId());
		intent.putExtra("claim",c);
		startActivity(intent);
	}

	/**
	 * Intended to return true if the object in question has been favourited
	 * @return
	 */
	public Boolean getFavouriteState() {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		DatabaseHelper dbh = new DatabaseHelper(this);
		
		try {
			Cursor cu;
			String[] selectArgs = { Integer.toString( claim.getId() ) };
			cu = dbh.getWritableDatabase().rawQuery("select f.* from Favorites f where f.ClaimId = ? and f.isFav = 1", selectArgs );
			Integer itemCount = cu.getCount();
			cu.close();
			
			if ( itemCount.equals(0) ) {
				return false;
			}
			return true;

		} catch (SQLException sqle){
			Log.e("SQLError",sqle.getMessage());
			throw sqle;
		} 
	}

	/**
	 * Intended to return true if a fav record exists for this claim regardless of it's status
	 * @return
	 */
	public Boolean favRecordExists( Claim claim, DatabaseHelper dbh ) {
		
		try {
			Cursor cu;
			String[] selectArgs = { Integer.toString( claim.getId() ) };
			cu = dbh.getWritableDatabase().rawQuery("select f.* from Favorites f where f.ClaimId = ?", selectArgs );
			Integer cuCount = cu.getCount();
			cu.close();
			
			if ( cuCount.equals( 0 ) ) {
				return false;
			}
			return true;
		} catch (SQLException sqle){
			Log.e("SQLError",sqle.getMessage());
			throw sqle;
		}
	}

	private void insertFavRecord( Claim claim, DatabaseHelper dbh ) {
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("INSERT INTO " + DatabaseHelper.FAVORITES_TABLE + " (Id,ClaimId,isFav) VALUES (null,?,?)");
		stmt.bindLong(1, claim.getId());
		stmt.bindLong(2, (isFav)?1L:0L );
		stmt.execute();
		stmt.close();
	}

	private void updateFavRecord( Claim claim, DatabaseHelper dbh ) {
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("UPDATE " + DatabaseHelper.FAVORITES_TABLE + " SET isfAV = ? WHERE ClaimId= ?");
		stmt.bindLong(2, claim.getId());
		stmt.bindLong(1, (isFav)?1L:0L );
		stmt.execute();
		stmt.close();
	}
	

	public void onAddFavorite(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		DatabaseHelper dbh = new DatabaseHelper(this);

		// Toggle the fav status
		isFav = ! isFav;
		
		setFavStatus( claim, dbh );

	}

}